package com.cke.yang.security.infra.config;

import com.cke.yang.common.domain.model.SecUserDetails;
import com.cke.yang.security.domain.entity.SecRole;
import com.cke.yang.security.domain.entity.SecUser;
import com.cke.yang.security.domain.repository.SecRoleRepository;
import com.cke.yang.security.infra.filter.JwtAuthenticationFilter;
import com.cke.yang.security.infra.handler.BaseAccessDeniedHandler;
import com.cke.yang.security.infra.handler.BaseLoginInvalidHandler;
import com.cke.yang.security.infra.mapper.SecUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

/**
 * 安全配置
 *
 * @author yuyang
 */
@Slf4j
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private BaseAccessDeniedHandler baseAccessDeniedHandler;
    @Autowired
    private BaseLoginInvalidHandler baseLoginInvalidHandler;
    @Autowired
    @Lazy
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .headers(headers -> headers
                    .frameOptions(HeadersConfigurer.FrameOptionsConfig::disable)
                )
                .authorizeHttpRequests(authorize -> authorize
                        // 放行api的部分接口
                        .requestMatchers("/api/security/sec-auth/login").permitAll()
                        // 保护除上述以外的API接口
                        .requestMatchers("/api/**").authenticated()
                        // 其他所有请求放行（前端路由）
                        .anyRequest().permitAll()
                )
                .sessionManagement(session -> session
                        // 无状态会话
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                .formLogin(AbstractHttpConfigurer::disable)
                .httpBasic(AbstractHttpConfigurer::disable)
                // 禁用默认登出，使用JWT无状态
                .logout(AbstractHttpConfigurer::disable)
                .exceptionHandling(exception -> exception
                        .authenticationEntryPoint(baseLoginInvalidHandler)
                        .accessDeniedHandler(baseAccessDeniedHandler)
                )
                // JWT不需要CSRF保护
                .csrf(AbstractHttpConfigurer::disable)
                // 启用CORS支持
                .cors(cors -> cors.configurationSource(corsConfigurationSource()))
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        return http.build();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        org.springframework.web.cors.CorsConfiguration configuration = new org.springframework.web.cors.CorsConfiguration();
        configuration.setAllowedOriginPatterns(java.util.List.of("*"));
        configuration.setAllowedMethods(java.util.List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(java.util.List.of("*"));
        configuration.setAllowCredentials(true);
        configuration.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new org.springframework.web.cors.UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }


    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    @Bean
    public UserDetailsService userDetailsService(SecUserMapper secUserMapper, SecRoleRepository secRoleRepository) {
        return username -> {
            log.debug("加载用户详情: {}", username);

            // 查找用户
            SecUser secUser = secUserMapper.selectOne(
                    new LambdaQueryWrapper<SecUser>().eq(SecUser::getUsername, username)
            );

            if (secUser == null) {
                log.warn("用户不存在: {}", username);
                throw new UsernameNotFoundException("用户不存在");
            }

            // 创建用户详情对象
            SecUserDetails userDetails = new SecUserDetails(secUser);

            // 加载用户的角色列表
            List<SecRole> userRoles = secRoleRepository.getRoleListByUserId(secUser.getUserId());

            if (!userRoles.isEmpty()) {
                SecRole defaultRole = null;

                // 优先使用用户表中的默认角色ID
                if (secUser.getDefaultRoleId() != null) {
                    defaultRole = userRoles.stream()
                            .filter(role -> role.getRoleId().equals(secUser.getDefaultRoleId()))
                            .findFirst()
                            .orElse(null);
                }

                // 如果默认角色ID不存在或无效，使用第一个角色
                if (defaultRole == null) {
                    defaultRole = userRoles.get(0);
                }

                userDetails.setCurrentRoleId(defaultRole.getRoleId());
                userDetails.setCurrentRoleName(defaultRole.getRoleName());
                log.debug("为用户 {} 设置默认角色: {} (ID: {})", username, defaultRole.getRoleName(), defaultRole.getRoleId());
            } else {
                log.warn("用户 {} 没有分配任何角色", username);
            }

            return userDetails;
        };
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}